package com.arron.ioAndNio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Classname TestBlockingNio
 * @Date 2020/8/27 23:54
 * @Created by 刘
 */
public class TestBlockingNio {

    //客户端
    public static void main(String[] args) throws IOException {

        //获取通道
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));

        //写文件通道
        FileChannel fileChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);

        //创建缓冲区
//        socketChannel
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //从缓冲区中读
        while (socketChannel.read(buffer) != -1){
            buffer.flip();
            fileChannel.write(buffer);
            buffer.clear();
        }
        //关闭通道
        socketChannel.close();
        fileChannel.close();

    }


}
